const { getByPrimary } = require("./DAO");
/**
 * 模糊查询用户数量
 * @param {*} key
 * @param {*} cb
 */
module.exports.countByKey = function (key, cb) {
  let sql = "SELECT count(*) as count FROM sp_manager";
  if (key) {
    sql += " WHERE mg_name LIKE ?";
    database.driver.execQuery(sql, ["%" + key + "%"], function (err, result) {
      console.log(err, result);
      if (err) return cb("查询执行出错");
      cb(null, result[0]["count"]);
    });
  } else {
    database.driver.execQuery(sql, function (err, result) {
      if (err) return cb("查询执行出错");
      cb(null, result[0]["count"]);
    });
  }
};

/**
 *根据关键词查找用户
 * @param {*} key
 * @param {*} offset
 * @param {*} limit
 * @param {*} cb
 */
module.exports.findByKey = function (key, offset, limit, cb) {
  let sql =
    "SELECT * FROM sp_manager as mgr LEFT JOIN sp_role as role ON mgr.role_id = role.role_id";
  if (key) {
    sql += " WHERE mg_name LIKE ? LIMIT ?,?";
    database.driver.execQuery(
      sql,
      ["%" + key + "%", offset, limit],
      function (err, managers) {
        if (err) return cb("查询执行出错");
        cb(null, managers);
      }
    );
  } else {
    sql += " LIMIT ?,? ";
    database.driver.execQuery(sql, [offset, limit], function (err, managers) {
      if (err) return cb("查询执行出错");
      cb(null, managers);
    });
  }
};

module.exports.exists = function (username, cb) {
  database.models.ManagerModel.exists(
    { mg_name: username },
    function (err, exists) {
      if (err) return cb(err + "查询失败");
      cb(null, exists);
    }
  );
};

module.exports.create = function (user, cb) {
  database.models.ManagerModel.create(user, cb);
};

module.exports.update = function (updateObj, cb) {
  //Find record by primary key.
  getByPrimary.get("ManagerModel", updateObj.mg_id, function (err, obj) {
    if (err) return cb(err);
    obj.save(updateObj, cb);
  });
};

module.exports.delete = function (id, cb) {
  database.models.ManagerModel.get(id, function (err, obj) {
    if (err) return cb(err);
    obj.remove(cb);
  });
};

module.exports.findOne = function (user, cb) {
  database.models.ManagerModel.find(user, function (err, person) {
    if (err) return cb(err);
    cb(null, person[0]);
  });
};
